package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachPlanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    public List<TeachplanDto> findTeachplanTree(Long courseId){
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    /**
     * 新增或修改课程计划
     * @param saveTeachplanDto
     */
    @Override
    public void saveTeachPlan(SaveTeachplanDto saveTeachplanDto) {
        Long id = saveTeachplanDto.getId();
        Integer grade = saveTeachplanDto.getGrade();
        if(id == null){
            //新增操作
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);

            //确定排序字段orderBy
            Long courseId = saveTeachplanDto.getCourseId();
            Long parentid = saveTeachplanDto.getParentid();
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            int maxOrder = 0;
            for (Teachplan teachplan1 : teachplans) {
                if(teachplan1.getOrderby() > maxOrder){
                    maxOrder = teachplan1.getOrderby();
                }
            }
            teachplan.setOrderby(maxOrder + 1);

            teachplanMapper.insert(teachplan);
        }else {
            //修改操作
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        }
    }

    /**
     * 删除课程计划
     * @param id
     */
    @Override
    public void deleteTeachPlan(Long id) {
        //根据ID查询
        Teachplan teachplan = teachplanMapper.selectById(id);
        int grade = teachplan.getGrade();
        //判断是章还是节
        if(grade == 1){
            //章
            List<Teachplan> list = teachplanMapper.getIdByParentId(id);
            if(list != null && list.size() > 0){
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
            }
        }else{
            //节
            Teachplan teachplan1 = teachplanMapper.selectById(id);
            TeachplanMedia byTeachPlanIdAndCourseId = teachplanMediaMapper.getByTeachPlanIdAndCourseId(teachplan1.getId(), teachplan1.getCourseId());
            teachplanMediaMapper.deleteById(byTeachPlanIdAndCourseId);

        }
        teachplanMapper.deleteById(id);
    }

    /**
     * 课程下移
     * @param id
     */
    @Override
    public void moveDown(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        int grade = teachplan.getGrade();
        Long courseId = teachplan.getCourseId();

        if(grade == 1){
            //章，章向下移动时，连着本章下的所有小节都要下移
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<Teachplan>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId()).eq(Teachplan::getGrade,1);
            List<Teachplan> teachPlans = teachplanMapper.selectList(queryWrapper);

            //根据orderBy值进行排序
            Collections.sort(teachPlans, new Comparator<Teachplan>() {
                @Override
                public int compare(Teachplan o1, Teachplan o2) {
                    return Integer.compare(o1.getOrderby(), o2.getOrderby());
                }
            });

            //判断该章下方是否还有章
            for(int i = 0; i < teachPlans.size(); i++){
                if(teachPlans.get(i).getOrderby() == teachplan.getOrderby() ){
                    if(i == teachPlans.size() - 1){
                        XueChengPlusException.cast("最后一章，无法下移");
                    }else{
                        Teachplan teachPlanNext = teachPlans.get(i + 1);
                        Integer orderby = teachPlanNext.getOrderby();
                        teachPlanNext.setOrderby(teachplan.getOrderby());
                        teachplan.setOrderby(orderby);
                        teachplanMapper.updateById(teachPlanNext);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }
                }
            }

        }else{
            //节
            //找到同一章下的所有小节teachPlans
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<Teachplan>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid()).eq(Teachplan::getGrade,2);
            List<Teachplan> teachPlans = teachplanMapper.selectList(queryWrapper);

            //根据orderBy值进行排序
            Collections.sort(teachPlans, new Comparator<Teachplan>() {
                @Override
                public int compare(Teachplan o1, Teachplan o2) {
                    return Integer.compare(o1.getOrderby(), o2.getOrderby());
                }
            });

            //判断该节下方是否还有节
            for(int i = 0; i < teachPlans.size(); i++){
                if(teachPlans.get(i).getOrderby() == teachplan.getOrderby() ){
                    if(i == teachPlans.size() - 1){
                        XueChengPlusException.cast("最后一节，无法下移");
                    }else{
                        Teachplan teachPlanNext = teachPlans.get(i + 1);
                        Integer orderby = teachPlanNext.getOrderby();
                        teachPlanNext.setOrderby(teachplan.getOrderby());
                        teachplan.setOrderby(orderby);
                        teachplanMapper.updateById(teachPlanNext);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 课程上移
     * @param id
     */
    @Override
    public void moveUp(Long id) {
        //当前课程
        Teachplan teachplan = teachplanMapper.selectById(id);
        int grade = teachplan.getGrade();
        Long courseId = teachplan.getCourseId();

        if(grade == 1){
            //章
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<Teachplan>();
            queryWrapper.eq(Teachplan::getCourseId,teachplan.getCourseId()).eq(Teachplan::getGrade,1);
            List<Teachplan> teachPlans = teachplanMapper.selectList(queryWrapper);
            //根据orderBy值从大到小进行排序
            Collections.sort(teachPlans, new Comparator<Teachplan>() {
                @Override
                public int compare(Teachplan o1, Teachplan o2) {
                    return Integer.compare(o2.getOrderby(), o1.getOrderby());
                }
            });

            //判断该章上方是否还有章
            for(int i = 0; i < teachPlans.size(); i++){
                if(teachPlans.get(i).getOrderby() == teachplan.getOrderby() ){
                    if(i == teachPlans.size() - 1){
                        XueChengPlusException.cast("第一章，无法上移");
                    }else{
                        Teachplan teachPlanNext = teachPlans.get(i + 1);
                        Integer orderby = teachPlanNext.getOrderby();
                        teachPlanNext.setOrderby(teachplan.getOrderby());
                        teachplan.setOrderby(orderby);
                        teachplanMapper.updateById(teachPlanNext);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }
                }
            }
        }else{
            //节
            //找到同一章下的所有小节teachPlans
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<Teachplan>();
            queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid()).eq(Teachplan::getGrade,2);
            List<Teachplan> teachPlans = teachplanMapper.selectList(queryWrapper);

            //根据orderBy值从大到小进行排序
            Collections.sort(teachPlans, new Comparator<Teachplan>() {
                @Override
                public int compare(Teachplan o1, Teachplan o2) {
                    return Integer.compare(o2.getOrderby(), o1.getOrderby());
                }
            });

            //判断该节下方是否还有节
            for(int i = 0; i < teachPlans.size(); i++){
                if(teachPlans.get(i).getOrderby() == teachplan.getOrderby() ){
                    if(i == teachPlans.size() - 1){
                        XueChengPlusException.cast("第一节，无法上移");
                    }else{
                        Teachplan teachPlanNext = teachPlans.get(i + 1);
                        Integer orderby = teachPlanNext.getOrderby();
                        teachPlanNext.setOrderby(teachplan.getOrderby());
                        teachplan.setOrderby(orderby);
                        teachplanMapper.updateById(teachPlanNext);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 课程计划绑定媒资
     * @param bindTeachPlanMediaDto
     */
    @Override
    public void associationMedia(BindTeachPlanMediaDto bindTeachPlanMediaDto) {

        Long teachPlanId = bindTeachPlanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachPlanId);
        if(teachplan == null){
            XueChengPlusException.cast("课程计划不存在");
        }

        //先删除原有记录
        LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId, bindTeachPlanMediaDto.getTeachplanId());
        int delete = teachplanMediaMapper.delete(queryWrapper);

        //再添加新纪录
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        BeanUtils.copyProperties(bindTeachPlanMediaDto, teachplanMedia);
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setMediaFilename(bindTeachPlanMediaDto.getFileName());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMedia.setMediaId(bindTeachPlanMediaDto.getMediaId());
        teachplanMediaMapper.insert(teachplanMedia);
    }
}
